#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
工具包
"""

__author__ = 'Lei Chen'

import yaml
import logging
import logging.config
import os

DIR = os.path.split(os.path.realpath(__file__))[0]
DIR = os.path.dirname(DIR)

LOG_CFG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '%(asctime)s - %(levelname)s - %(message)s'
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'DEBUG',
            'formatter': 'simple',
            'stream': 'ext://sys.stdout'
        },
        'info_file_handler': {
            'class': 'logging.handlers.RotatingFileHandler',
            'level': 'INFO',
            'formatter': 'simple',
            'filename': DIR + '/logs/info.log',
            'maxBytes': 10485760,
            'backupCount': 20,
            'encoding': 'utf8'
        },
        'error_file_handler': {
            'class': 'logging.handlers.RotatingFileHandler',
            'level': 'ERROR',
            'formatter': 'simple',
            'filename': DIR + '/logs/error.log',
            'maxBytes': 10485760,
            'backupCount': 20,
            'encoding': 'utf8'
        }
    },
    'loggers': {
        'my_module': {
            'level': 'ERROR',
            'handlers': ['info_file_handler'],
            'propagate': 'no'
        }
    },
    'root': {
        'level': 'INFO',
        'handlers': ['console', 'info_file_handler', 'error_file_handler']
    }
}


def setup_logging(log_file=None):
    if log_file:
        LOG_CFG.get('handlers').get('info_file_handler')['filename'] = log_file
    else:
        path = os.path.join(DIR, 'logs')
        if not os.path.exists(path):
            os.mkdir(path)
    logging.config.dictConfig(LOG_CFG)


class YamlParser(object):
    def __init__(self):
        pass

    def _data(self, dir, fileName):
        _yaml = self.get(dir + '/' + fileName)
        if _yaml:
            data = {'title': _yaml.get('title'), 'path': '{0}/{1}'.format(dir, fileName), 'dir': dir, 'is_dir': False}
            if _yaml.get('dubbo'):
                data['type'] = 'dubbo'
            else:
                data['type'] = 'api'
        return data

    def list(self, dir):
        _datas = []
        dir = os.path.join(DIR, dir)
        for fileName in os.listdir(dir):
            if os.path.splitext(fileName)[1] == '.yaml':
                _datas.append(self._data(dir, fileName))
            else:
                path = os.path.join(dir, fileName)
                _datas.append({'title': fileName, 'path': path, 'dir': dir, 'is_dir': True})
        return _datas

    def valid(self, path):
        content = []
        config = self.get(path)
        if config:
            if not config.get('title'):
                content.append('title not exist')
            if not config.get('dubbo') and not config.get('system'):
                content.append('system not exist')

            if config.get('test'):
                testes = config.get('test')
                for index in range(len(testes)):
                    test = testes[index]
                    if not test.get('id'):
                        content.append('[{0}] -> id is exist'.format(index))
                    if not test.get('group'):
                        content.append('[{0}] -> group is exist'.format(index))
                    if not test.get('name'):
                        content.append('[{0}] -> name is exist'.format(index))
                    if not test.get('server'):
                        content.append('[{0}] -> server is exist'.format(index))
                    if not test.get('method'):
                        content.append('[{0}] -> method not exist'.format(index))
                    # if not config.get('dubbo'):
                    # if not test.get('headers'):
                    #     content.append('[{0}] -> headers not exist'.format(index))
                    # if not test.get('params'):
                    #     content.append('[{0}] -> params not exist'.format(index))
            else:
                content.append('test not exist')

        return content

    def get(self, path):
        if not os.path.isdir(path):
            with open(path, encoding='UTF-8') as f:
                result = yaml.load(f)
                return result
        else:
            return None


if __name__ == '__main__':
    logging.error('dfdfdfd')


def main():
    pass


if __name__ == '__main__':
    main()
